var loginBaseUrl = sessionStorage.getItem("loginBaseUrl");
if("undefined" != typeof loginOptions){
    if(loginOptions.env){
        loginBaseUrl = loginOptions.env
        sessionStorage.setItem("loginBaseUrl", loginBaseUrl);
    }
}

if(window.location.href.indexOf('nucCode') >0 ){
  loginRequired("nucCode",GetQueryString('nucCode'))
}

hookAjax = function(proxy) {
  window._ahrealxhr = window._ahrealxhr || XMLHttpRequest;
  XMLHttpRequest = function() {
    this.xhr = new window._ahrealxhr();
    for (var attr in this.xhr) {
      var type = "";
      try {
        type = typeof this.xhr[attr];
      } catch (e) {}
      if (type === "function") {
        this[attr] = hookfun(attr);
      } else {
        Object.defineProperty(this, attr, {
          get: getFactory(attr),
          set: setFactory(attr)
        });
      }
    }
  };

  function getFactory(attr) {
    return function() {
      var v = this.hasOwnProperty(attr + "_")
        ? this[attr + "_"]
        : this.xhr[attr];
      var attrGetterHook = (proxy[attr] || {})["getter"];
      return (attrGetterHook && attrGetterHook(v, this)) || v;
    };
  }

  function setFactory(attr) {
    return function(v) {
      var xhr = this.xhr;
      var that = this;
      var hook = proxy[attr];
      if (typeof hook === "function") {
        xhr[attr] = function() {
          proxy[attr](that) || v.apply(xhr, arguments);
        };
      } else {
        //If the attribute isn't writeable, generate proxy attribute
        var attrSetterHook = (hook || {})["setter"];
        v = (attrSetterHook && attrSetterHook(v, that)) || v;
        try {
          xhr[attr] = v;
        } catch (e) {
          this[attr + "_"] = v;
        }
      }
    };
  }

  function hookfun(fun) {
    return function() {
      var args = [].slice.call(arguments);
      if (proxy[fun] && proxy[fun].call(this, args, this.xhr)) {
        return;
      }
      return this.xhr[fun].apply(this.xhr, args);
    };
  }
  return window._ahrealxhr;
};
unHookAjax = function() {
  if (window._ahrealxhr) XMLHttpRequest = window._ahrealxhr;
  window._ahrealxhr = undefined;
};

hookAjax({
  onreadystatechange: function(xhr) {
    hookHandle(xhr)
  },
  onload: function(xhr) {
    hookHandle(xhr);
  },
  open: function(arg, xhr) { 
    requestUrl = arg[1]
  },
  setRequestHeader: function(data) {
    if(data[0] == 'X-Requested-With') {
      xhrhaveXrw = true
    }
  },
  send: function() {
    if (this.xhr.readyState == 1) {
      if(xhrhaveXrw == false) {
        this.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");  
      }
      this.xhr.setRequestHeader("Login-Type", "nuc");
      var setAuth = true
      for(j = 0,len=exceptUrlArr.length; j < len; j++) {
        if(exceptUrlArr[j].test(requestUrl)){
          setAuth = false
          break
        }
      }
      if(setAuth == true){
        var auth = sessionStorage.getItem("_a");
        if (auth != null) {
          this.xhr.setRequestHeader("Authorization", auth);
        }
      }
    }
  }
});

var requestUrl = ''
var xhrhaveXrw = false

//拦截处理
function hookHandle(xhr) {
  var responseHeader = xhr.getAllResponseHeaders().toLowerCase();
  if(responseHeader.indexOf('eventtype')==-1 && responseHeader.indexOf('login-required') == -1){
    return
  }

  //gateway
  var lr = xhr.getResponseHeader("Login-required");
  if(lr === "True" && xhr.status === 200) {
    var oauthUrl = xhr.getResponseHeader("Oauth-URL");
    if(oauthUrl) {
      window.location.href = oauthUrl
    }
  }

  var EventType = xhr.getResponseHeader("EventType");
  var EventCode = xhr.getResponseHeader("EventCode");
  if (EventType === null && EventCode === null) {
    return;
  }
  EventType = EventType.toLowerCase();
  EventCode = EventCode.toLowerCase();
  if (EventType === "exception" && EventCode === "500") {
    console.log("exception!!!");
  }
  var LoginEvent = xhr.getResponseHeader("LoginEvent");
  if (EventType === "loginrequired" && EventCode === "platform.nosession") {
    if(LoginEvent && "nojump" == LoginEvent.toLowerCase()) {
      loginRequired("nojump");
    } else {
      loginRequired();
    }
  }
}

//登录处理
function loginRequired(LoginEvent, nucCode) {
  var crossDomainLoginUrl = loginBaseUrl + "/LoginApp/v1/crossDomainLogin";
  if(LoginEvent == "nojump") {
    crossDomainLoginUrl += "?jump=false"
  }
  if(LoginEvent == "nucCode") {
    crossDomainLoginUrl += "?nucCode="+ nucCode
  }
  $.getScript(crossDomainLoginUrl);
}

//logout
var platform_logout = function(options) {
  //delete seesion cookie
  sessionStorage.removeItem('_a')
  document.cookie = "_a=0" + ";expires="+new Date().toUTCString(); 
  var path = loginBaseUrl + "/LoginApp/v1/logout";
  var redirect_url = window.location.href;
  if (window.location.hash !== "") {
    if(options && options.home == true){
      redirect_url = window.location.href.replace(window.location.hash, "#/");
    }
  }
  path += "?redirectUrl=" + redirect_url;
  window.location.href = path;
};

//not login
function loginFail(obj) {
  if (!obj.state) {
    if(!obj.data.jump && obj.data.jump != false) {
      jumpLoginPage("");
    }
  }
}

//has logined
function loginSuccess(obj) {
    if (obj.state) {
      //write session
      sessionStorage.setItem("_a", obj.data.token);
      //custom cookie domain
      var cookieDomain;
      if("undefined" != typeof loginOptions){
        if(loginOptions.cookieDomain) {
          cookieDomain = loginOptions.cookieDomain
        }
      }
      //write cookie
      if(cookieDomain){
        document.cookie = "_a=" + obj.data.token + ";path=/;domain="+cookieDomain;
      } else{
        var domain = /[^.\/]+\.[^.\/]+$/.exec(window.location.hostname)
        if(domain != null&&(!isValidIP(window.location.hostname))){
          var domainStr = domain[0];
          //sit & uat env
          var sitdomain = 'sit.'+domainStr
          var uatdomain = 'uat.'+domainStr
          if(window.location.hostname.indexOf(sitdomain) > 0){
            domainStr = sitdomain
          } else if (window.location.hostname.indexOf(uatdomain) > 0){
            domainStr = uatdomain
          }
          document.cookie = "_a=" + obj.data.token + ";path=/;domain="+domainStr;
          if(obj.data.cmToken) {
            document.cookie = "cmToken=" + obj.data.cmToken + ";path=/;domain="+domainStr;
          }
        } else{
          document.cookie = "_a=" + obj.data.token + ";path=/;";
          if(obj.data.cmToken) {
            document.cookie = "cmToken=" + obj.data.cmToken + ";path=/;domain="+domainStr;
          }
        }
      }
      if(window.location.href.indexOf('nucCode') > 0){
        var nucCodeStr = "nucCode=" + GetQueryString('nucCode');
        if(window.location.href.indexOf('?'+nucCodeStr) > 0){
          window.location.href = window.location.href.replace('?'+nucCodeStr, '')
        } else if(window.location.href.indexOf('&'+nucCodeStr) > 0){
          window.location.href = window.location.href.replace('&'+nucCodeStr, '')
        }
      } else{
        window.location.reload();
      }
    } else {
      jumpLoginPage("");
    }
  }

//jump to login page
function jumpLoginPage(redirect_url) {
  if (redirect_url == "") {
    redirect_url = window.location.href;
  }
  var url = loginBaseUrl +
  "/LoginWeb/bootlogin/v2.1/login.html?"

  if("undefined" != typeof loginOptions){
    if(loginOptions.intranet == true) {
      url = url.replace('v2.1','v1')
    }
    loginOptions.jsVersion = "v1.1";
    if(loginOptions.redirectUrl) {
      redirect_url = loginOptions.redirectUrl
    }
    url += "loginOptions="+window.btoa(JSON.stringify(loginOptions))
    url += "&redirect_url=" + encodeURIComponent(redirect_url);
  } else {
    url += "redirect_url=" + encodeURIComponent(redirect_url);
  }
  window.location.href = url;
}

function isValidIP(ip) {
  var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  return reg.test(ip);
} 

var exceptUrlArr = [
  /^https:\/\/cos(.*)\/cos-upload\/.*/
]

function GetQueryString(name) {
  var after = window.location.href.split('?')[1];
  if (after) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
      var r = after.match(reg);
      if (r != null) {
      return decodeURIComponent(r[2]);
      } else {
      return null;
      }
  }
}